﻿#include "gofgame/jumpdown/layer/ListLayer.h"
#include "gofgame/jumpdown/io/LocalInformation.h"
#include "gofgame/jumpdown/Configuration.h"


using namespace cocos2d::extension;
using namespace gofgame::jumpdown::layer;
using namespace gofgame::jumpdown::io;
using namespace gofgame::jumpdown::util;

enum {
	kLocalTitleTag,
	kNetTitleTag
};

bool ListLayer::init() {
	if (!CCLayer::init()) {
		return false;
	}
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	//背景
	CCSprite *bg = CCSprite::create("listBg.png");
	bg->setPosition(ccp(winSize.width / 2, winSize.height / 2));
	bg->setScaleX((float)winSize.width / bg->getContentSize().width);
	bg->setScaleY((float)winSize.height / bg->getContentSize().height);
	this->addChild(bg);
	//标题
	CCSprite *localTitle = CCSprite::create("localTitle.png");
	localTitle->setPosition(ccp(winSize.width / 2, winSize.height * 0.9F));
	localTitle->setTag(kLocalTitleTag);
	CCSprite *globalTitle = CCSprite::create("globalTitle.png");
	globalTitle->setPosition(ccp(winSize.width / 2, winSize.height * 0.9F));
	globalTitle->setTag(kNetTitleTag);
	globalTitle->setVisible(false);
	this->addChild(localTitle);
	this->addChild(globalTitle);
	//表格
	tableView = CCTableView::create(this,CCSizeMake(winSize.width * 0.8F, winSize.height * 0.5F));
	tableView->setDirection(kCCScrollViewDirectionVertical);
	tableView->setPosition(ccp(winSize.width * 0.1F, winSize.height * 0.22F));
	this->addChild(tableView);
	tableView->setDelegate(this);
	//tableView->setVerticalFillOrder(kCCTableViewFillTopDown);
	tableView->reloadData();
	//按钮
	//1.本地网络切换
	CCMenuItemImage *menuLocal = CCMenuItemImage::create("netListButton.png", "netListButton.png");
	menuLocal->setScaleX(winSize.width * 0.2F / menuLocal->getContentSize().width);
	menuLocal->setScaleY(winSize.height * 0.06F / menuLocal->getContentSize().height);
	CCMenuItemImage *menuNel = CCMenuItemImage::create("localListButton.png", "localListButton.png");
	menuNel->setScaleX(winSize.width * 0.2F / menuNel->getContentSize().width);
	menuNel->setScaleY(winSize.height * 0.06F / menuNel->getContentSize().height);
	CCMenuItemToggle *menuToggle = CCMenuItemToggle::createWithTarget(this, menu_selector(ListLayer::menuToggleCallback), menuLocal, menuNel, NULL);
	//2.上传按钮
	CCMenuItemImage *menuUpdate = CCMenuItemImage::create("updateListButton.png", "updateListButton.png", this, menu_selector(ListLayer::menuUpdateCallback));
	menuUpdate->setScaleX(winSize.width * 0.2F / menuUpdate->getContentSize().width);
	menuUpdate->setScaleY(winSize.height * 0.06F / menuUpdate->getContentSize().height);
	CCMenu *menuGroup = CCMenu::create(menuToggle, menuUpdate,NULL);
	menuGroup->alignItemsHorizontallyWithPadding(40);
	menuGroup->setPosition(ccp(winSize.width * 0.5F, winSize.height * 0.15F));
	this->addChild(menuGroup);
	//返回按钮
	CCMenuItemImage *menuBack = CCMenuItemImage::create("backButton.png", "backButton.png", this, menu_selector(ListLayer::menuBackCallback));
	menuBack->setScaleX(winSize.width * 0.1F / menuBack->getContentSize().width);
	menuBack->setScaleY(winSize.width * 0.1F / menuBack->getContentSize().width);
	CCMenu *menuBackGroup = CCMenu::create(menuBack, NULL);
	menuBackGroup->setPosition(winSize.width-30,winSize.height-30);
	this->addChild(menuBackGroup);
	return true;
}

void ListLayer::menuBackCallback(CCObject *sender) {
	CCDirector::sharedDirector()->popScene();
}


void ListLayer::menuToggleCallback(CCObject *sender) {
	CCMenuItemToggle *cmit =  dynamic_cast<CCMenuItemToggle*>(sender);
	CCSprite *localTitle = static_cast<CCSprite*>(this->getChildByTag(kLocalTitleTag));
	CCSprite *netTitle = static_cast<CCSprite*>(this->getChildByTag(kNetTitleTag));
	if(cmit->getSelectedIndex() == 1) {
		localTitle->setVisible(false);
		netTitle->setVisible(true);
		initDataWithNet();
	} else {
		initDataWithLocalInformation();
		this->tableView->reloadData();
		localTitle->setVisible(true);
		netTitle->setVisible(false);
	}
}

void ListLayer::menuUpdateCallback(CCObject *sender) {
	LocalInformation localInformation = LocalInformation::load();
	if(localInformation.count() > 0) {
		Score score = localInformation[0];
		jdc->submitScore(score.getUserName(), score.getLevel());
	}
}

ListLayer *ListLayer::createListLayer() {
	ListLayer *ll = new ListLayer();
	ll->initDataWithLocalInformation();
	if(!ll->init()) {
		delete ll;
		return nullptr;
	}
	ll->autorelease();
	return ll;
}

void ListLayer::tableCellTouched(CCTableView* table, CCTableViewCell* cell) {
	CCLOG("cell touched at index: %i", cell->getIdx());
}

CCSize ListLayer::cellSizeForTable(CCTableView *table) {
	return CCSizeMake(420, 60);
}

ListCell* ListLayer::tableCellAtIndex(CCTableView *table, unsigned int idx) {
	return m_dataVector.at(idx);
}

unsigned int ListLayer::numberOfCellsInTableView(CCTableView *table) {
	return m_dataVector.size();
}

void ListLayer::initDataWithLocalInformation() {
	LocalInformation li = LocalInformation::load();
	this->m_dataVector.clear();

	for(auto index = 0;index < li.count(); index++) {
		Score score = li[index];
		int rank = li.getRank(score.getLevel());
		rank++;
		ListCell *lc = ListCell::createListCell(rank, score.getUserName(), score.getLevel());
		this->m_dataVector.push_back(lc);
	};
	if(this->m_dataVector.size()!=0){
		std::qsort(&this->m_dataVector[0],this->m_dataVector.size(),sizeof(&this->m_dataVector),sort_data);
	}
}

void ListLayer::initDataWithNet() {
	jdc->queryScores(0,10);
}

int sort_data(const void* a, const void* b){
	ListCell *pa = *( (ListCell**) a );
	ListCell *pb = *( (ListCell**) b );
	if (pa->getRank() > pb->getRank())
		return -1;
	else if (pa->getRank() < pb->getRank())
		return 1;
	return 0;
}

ListLayer::ListLayer(){
	*&this->jdc = new JumpDownController();
	this->jdc->addQueryScoreListener([this](Page<Score> *page){
		if(page != nullptr) {
			this->m_dataVector.clear();
			for (auto index=0;index < page->count();index++) {
				Score score = (*page)[index];
				int rank = index+1;
				ListCell *lc = ListCell::createListCell(rank, score.getUserName(), score.getLevel());
				CCLOG("name is %s", score.getUserName());
				this->m_dataVector.insert(this->m_dataVector.begin(), lc);
			}
			this->tableView->reloadData();
		} else {
			CCMessageBox("抱歉获取网络排名失败，请检查网络连接后重试","提示");
		}
	});

	this->jdc->addSubmitScoreListener([](int* result){
		if(nullptr != result) {
			CCMessageBox("上传排名成功","提示");
		}else {
			CCMessageBox("上传排名失败，请重新上传","提示");
		}
	});
}

ListLayer::~ListLayer() {
	this->jdc->dispose();
}